<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>spot.gitagent.io - Discover your next spot!</title>
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <link rel="icon" type="image/svg+xml" href="/favicon.svg">
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="styles_doro.css">
    <!-- Supabase客户端 -->
    <script src="./supabase-client.js"></script>
    <style>
        /* 欢迎消息动画 */
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* 指南针Logo样式 - 响应式设计 */
        .compass-logo {
            display: inline-block;
            /* 使用clamp确保Logo在不同屏幕尺寸下保持适当大小 */
            width: clamp(28px, 4vw, 36px);
            height: clamp(28px, 4vw, 36px);
            border: 3px solid #333;
            border-radius: 50%;
            position: relative;
            margin-right: 12px;
            vertical-align: middle;
            background: white;
            /* 确保Logo保持圆形 */
            flex-shrink: 0;
            aspect-ratio: 1 / 1;
        }
        
        .compass-logo::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            /* 指针大小相对于Logo大小自适应 */
            border-left: clamp(4px, 0.8vw, 7px) solid transparent;
            border-right: clamp(4px, 0.8vw, 7px) solid transparent;
            border-bottom: clamp(8px, 1.6vw, 14px) solid #1976d2;
            transform: translate(-50%, -50%);
        }
        
        .compass-logo::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            /* 指针大小相对于Logo大小自适应 */
            border-left: clamp(4px, 0.8vw, 7px) solid transparent;
            border-right: clamp(4px, 0.8vw, 7px) solid transparent;
            border-top: clamp(8px, 1.6vw, 14px) solid #d32f2f;
            transform: translate(-50%, -50%);
        }
        
        .compass-logo .north {
            position: absolute;
            top: 2px;
            left: 50%;
            transform: translateX(-50%);
            font-size: clamp(8px, 1.2vw, 12px);
            font-weight: bold;
            color: #333;
        }
        
        .compass-logo .east {
            position: absolute;
            right: 2px;
            top: 50%;
            transform: translateY(-50%);
            font-size: clamp(8px, 1.2vw, 12px);
            font-weight: bold;
            color: #333;
        }
        
        .compass-logo .south {
            position: absolute;
            bottom: 2px;
            left: 50%;
            transform: translateX(-50%);
            font-size: clamp(8px, 1.2vw, 12px);
            font-weight: bold;
            color: #333;
        }
        
        .compass-logo .west {
            position: absolute;
            left: 2px;
            top: 50%;
            transform: translateY(-50%);
            font-size: clamp(8px, 1.2vw, 12px);
            font-weight: bold;
            color: #333;
        }
        
        .app-title-text {
            vertical-align: middle;
        }
    </style>
    
    <!-- 关键函数定义 - 确保在HTML解析前就可用 -->
    <script>
        // 全局函数定义 - 立即可用
        function toggleLanguageDropdown() {
            console.log('toggleLanguageDropdown 被调用');
            const dropdown = document.getElementById('language-dropdown');
            if (dropdown) {
                dropdown.classList.toggle('hidden');
                console.log('语言下拉菜单切换成功');
            } else {
                console.error('找不到 language-dropdown 元素');
            }
        }

        function toggleUserMenu() {
            console.log('toggleUserMenu 被调用');
            const dropdown = document.getElementById('user-dropdown');
            if (dropdown) {
                dropdown.classList.toggle('hidden');
                console.log('用户菜单切换成功');
            } else {
                console.error('找不到 user-dropdown 元素');
            }
        }

        function toggleNavigationPanel() {
            console.log('toggleNavigationPanel 被调用');
            const collapsibleSettings = document.getElementById('collapsibleNavigationSettings');
            const toggleText = document.getElementById('navigation-toggle-text');
            const t = translations[currentLanguage] || translations['zh'];
            
            if (collapsibleSettings) {
                // 获取计算后的样式来判断当前状态
                const computedStyle = window.getComputedStyle(collapsibleSettings);
                const isVisible = computedStyle.display !== 'none';
                
                if (isVisible) {
                    collapsibleSettings.style.display = 'none';
                    if (toggleText) toggleText.textContent = t.showNavigationPanel || '显示导航面板';
                    console.log('导航设置区域已隐藏');
                } else {
                    collapsibleSettings.style.display = 'block';
                    if (toggleText) toggleText.textContent = t.hideNavigationPanel || '隐藏导航面板';
                    console.log('导航设置区域已显示');
                }
            } else {
                console.error('找不到 collapsibleNavigationSettings 元素');
            }
        }
        
        function toggleTravelGuide() {
            console.log('toggleTravelGuide 被调用');
            const travelGuideGenerator = document.getElementById('travelGuideGenerator');
            const toggleText = document.getElementById('travel-guide-toggle-text');
            const t = translations[currentLanguage] || translations['zh'];
            
            if (travelGuideGenerator) {
                // 获取计算后的样式来判断当前状态
                const computedStyle = window.getComputedStyle(travelGuideGenerator);
                const isVisible = computedStyle.display !== 'none';
                
                if (isVisible) {
                    travelGuideGenerator.style.display = 'none';
                    if (toggleText) toggleText.textContent = t.showTravelGuide || '显示生成导航';
                    console.log('一句话生成导航区域已隐藏');
                } else {
                    travelGuideGenerator.style.display = 'block';
                    if (toggleText) toggleText.textContent = t.hideTravelGuide || '隐藏生成导航';
                    console.log('一句话生成导航区域已显示');
                }
            } else {
                console.error('找不到 travelGuideGenerator 元素');
            }
        }
        
        // 保持兼容性的旧函数
        function toggleSettings() {
            toggleNavigationPanel();
        }

        // 检查登录状态的函数
        function checkLoginStatus() {
            const token = localStorage.getItem('access_token');
            return !!token;
        }

        // Supabase认证状态监听
        async function initializeSupabaseAuth() {
            try {
                // 检查URL中的认证错误
                checkAuthErrors();
                
                if (window.supabaseAuth) {
                    // 监听认证状态变化
                    window.supabaseAuth.onAuthStateChange((isAuthenticated, user, event) => {
                        console.log('🔐 主页面认证状态变化:', event, isAuthenticated, user?.email);
                        
                        if (isAuthenticated && user) {
                            // 用户已认证（包括邮件验证成功）
                            localStorage.setItem('access_token', 'supabase_authenticated');
                            localStorage.setItem('user_id', user.id);
                            localStorage.setItem('user_email', user.email);
                            localStorage.setItem('user_username', user.user_metadata?.username || user.email.split('@')[0]);
                            
                            // 更新用户界面
                            checkAuthStatus();
                            
                            // 如果是邮件验证成功，显示欢迎消息
                            if (event === 'SIGNED_IN' && user.email_confirmed_at) {
                                showWelcomeMessage(user);
                            }
                        } else {
                            // 用户未认证
                            localStorage.removeItem('access_token');
                            localStorage.removeItem('user_id');
                            localStorage.removeItem('user_email');
                            localStorage.removeItem('user_username');
                            
                            // 更新用户界面为未登录状态
                            checkAuthStatus();
                        }
                    });
                }
            } catch (error) {
                console.error('❌ Supabase认证初始化失败:', error);
            }
        }

        // 检查URL中的认证错误
        function checkAuthErrors() {
            const urlParams = new URLSearchParams(window.location.search);
            const hashParams = new URLSearchParams(window.location.hash.substring(1));
            
            // 检查URL参数和hash参数中的错误
            const error = urlParams.get('error') || hashParams.get('error');
            const errorCode = urlParams.get('error_code') || hashParams.get('error_code');
            const errorDescription = urlParams.get('error_description') || hashParams.get('error_description');
            
            if (error) {
                console.log('🔍 检测到认证错误:', { error, errorCode, errorDescription });
                
                let message = '';
                if (errorCode === 'otp_expired') {
                    message = '📧 邮件验证链接已过期，请重新注册或重新发送验证邮件。';
                } else if (error === 'access_denied') {
                    message = '❌ 邮件验证失败，请检查链接是否正确或重新发送验证邮件。';
                } else {
                    message = `❌ 认证错误: ${errorDescription || error}`;
                }
                
                showErrorMessage(message);
                
                // 清理URL中的错误参数
                setTimeout(() => {
                    const cleanUrl = window.location.origin + window.location.pathname;
                    window.history.replaceState({}, document.title, cleanUrl);
                }, 3000);
            }
        }

        // 显示错误消息
        function showErrorMessage(message) {
            const errorDiv = document.createElement('div');
            errorDiv.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
                color: white;
                padding: 15px 20px;
                border-radius: 10px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 10000;
                max-width: 400px;
                font-size: 14px;
                line-height: 1.4;
                animation: slideInRight 0.3s ease-out;
            `;
            errorDiv.textContent = message;
            
            // 添加关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.innerHTML = '×';
            closeBtn.style.cssText = `
                position: absolute;
                top: 5px;
                right: 8px;
                background: none;
                border: none;
                color: white;
                font-size: 18px;
                cursor: pointer;
                padding: 0;
                width: 20px;
                height: 20px;
            `;
            closeBtn.onclick = () => document.body.removeChild(errorDiv);
            errorDiv.appendChild(closeBtn);
            
            document.body.appendChild(errorDiv);
            
            // 8秒后自动消失
            setTimeout(() => {
                if (document.body.contains(errorDiv)) {
                    document.body.removeChild(errorDiv);
                }
            }, 8000);
        }

        // 显示欢迎消息
        function showWelcomeMessage(user) {
            const message = `🎉 欢迎 ${user.user_metadata?.username || user.email.split('@')[0]}！邮箱验证成功，您现在可以使用所有功能了。`;
            
            // 创建欢迎提示
            const welcomeDiv = document.createElement('div');
            welcomeDiv.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 15px 20px;
                border-radius: 10px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 10000;
                max-width: 350px;
                font-size: 14px;
                line-height: 1.4;
                animation: slideInRight 0.3s ease-out;
            `;
            welcomeDiv.textContent = message;
            
            // 添加关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.innerHTML = '×';
            closeBtn.style.cssText = `
                position: absolute;
                top: 5px;
                right: 8px;
                background: none;
                border: none;
                color: white;
                font-size: 18px;
                cursor: pointer;
                padding: 0;
                width: 20px;
                height: 20px;
            `;
            closeBtn.onclick = () => document.body.removeChild(welcomeDiv);
            welcomeDiv.appendChild(closeBtn);
            
            document.body.appendChild(welcomeDiv);
            
            // 5秒后自动消失
            setTimeout(() => {
                if (document.body.contains(welcomeDiv)) {
                    document.body.removeChild(welcomeDiv);
                }
            }, 5000);
        }

        // 需要登录的功能检查
        function requireLogin(callback, ...args) {
            if (checkLoginStatus()) {
                // 已登录，执行回调函数
                callback.apply(this, args);
            } else {
                // 未登录，打开新窗口进行登录
                const loginUrl = window.location.origin + '/login.html';
                const loginWindow = window.open(loginUrl, 'login', 'width=500,height=700,scrollbars=yes,resizable=yes,centerscreen=yes');
                
                // 监听来自登录窗口的消息
                const messageHandler = (event) => {
                    if (event.origin !== window.location.origin) return;
                    
                    if (event.data.type === 'login-success') {
                        console.log('登录成功，执行原始操作');
                        window.removeEventListener('message', messageHandler);
                        
                        // 更新用户界面
                        checkAuthStatus();
                        
                        // 执行原始操作
                        setTimeout(() => {
                            callback.apply(this, args);
                        }, 500);
                    }
                };
                
                window.addEventListener('message', messageHandler);
                
                // 监听窗口关闭事件
                const checkClosed = setInterval(() => {
                    if (loginWindow.closed) {
                        clearInterval(checkClosed);
                        window.removeEventListener('message', messageHandler);
                        
                        // 检查是否登录成功（备用检查）
                        if (checkLoginStatus()) {
                            console.log('检测到登录状态，执行原始操作');
                            checkAuthStatus();
                            callback.apply(this, args);
                        }
                    }
                }, 1000);
                
                console.log('用户未登录，已打开登录窗口');
            }
        }
        
        console.log('✅ 关键函数已在头部定义');
        
        // 旅游导航生成相关函数
        let currentTravelGuide = null; // 存储当前生成的旅游导航
        
        // 字符计数功能
        function updateCharCount() {
            const textarea = document.getElementById('travel-prompt');
            const counter = document.getElementById('char-count');
            if (textarea && counter) {
                counter.textContent = textarea.value.length;
            }
        }
        
        // 清空输入
        function clearTravelPrompt() {
            const textarea = document.getElementById('travel-prompt');
            if (textarea) {
                textarea.value = '';
                updateCharCount();
            }
        }
        
        // 生成旅游导航图
        async function generateTravelGuide() {
            const promptText = document.getElementById('travel-prompt').value.trim();
            if (!promptText) {
                alert('请输入您的旅游需求！');
                return;
            }
            
            const loadingEl = document.getElementById('guide-loading');
            const resultsEl = document.getElementById('travel-guide-results');
            
            // 显示加载状态
            if (loadingEl) loadingEl.style.display = 'block';
            if (resultsEl) resultsEl.style.display = 'none';
            
            try {
                console.log('开始生成旅游导航，用户输入:', promptText);
                
                // 调用后端API生成旅游导航
                const response = await fetch(`${API_BASE_URL}/api/travel/generate-guide`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                    },
                    body: JSON.stringify({
                        prompt: promptText,
                        language: currentLanguage || 'zh'
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                console.log('旅游导航生成成功:', data);
                
                currentTravelGuide = data;
                displayTravelGuide(data);
                
            } catch (error) {
                console.error('生成旅游导航失败:', error);
                
                // 显示模拟数据用于测试
                const mockData = generateMockTravelGuide(promptText);
                currentTravelGuide = mockData;
                displayTravelGuide(mockData);
                
                console.log('使用模拟数据展示结果');
            } finally {
                // 隐藏加载状态
                if (loadingEl) loadingEl.style.display = 'none';
            }
        }
        
        // 生成模拟数据
        function generateMockTravelGuide(prompt) {
            return {
                title: '为您定制的旅游导航图',
                summary: '根据您的需求，为您推荐以下精选景点和路线',
                attractions: [
                    {
                        id: 1,
                        name: '天安门广场',
                        rating: 4.8,
                        description: '中华人民共和国的象征，世界上最大的城市广场之一，承载着深厚的历史文化底蕴。',
                        category: '历史文化',
                        estimatedTime: '2-3小时',
                        ticketPrice: '免费',
                        location: { lat: 39.9042, lng: 116.4074 }
                    },
                    {
                        id: 2,
                        name: '故宫博物院',
                        rating: 4.9,
                        description: '明清两代的皇家宫殿，现为世界上最大的古代宫殿建筑群，珍藏着大量珍贵文物。',
                        category: '历史文化',
                        estimatedTime: '4-6小时',
                        ticketPrice: '60元',
                        location: { lat: 39.9163, lng: 116.3972 }
                    },
                    {
                        id: 3,
                        name: '王府井小吃街',
                        rating: 4.3,
                        description: '北京最著名的美食街之一，汇聚了各种传统小吃和特色美食，是品尝北京味道的绝佳去处。',
                        category: '美食',
                        estimatedTime: '1-2小时',
                        ticketPrice: '按消费',
                        location: { lat: 39.9097, lng: 116.4109 }
                    }
                ],
                route: {
                    totalDistance: '约15公里',
                    estimatedDuration: '1天',
                    transportation: '地铁+步行'
                }
            };
        }
        
        // 显示旅游导航结果
        function displayTravelGuide(data) {
            const resultsEl = document.getElementById('travel-guide-results');
            const attractionsListEl = document.getElementById('attractions-list');
            
            if (!resultsEl || !attractionsListEl) return;
            
            // 生成景点列表HTML
            let attractionsHTML = '';
            if (data.attractions && data.attractions.length > 0) {
                attractionsHTML = data.attractions.map(attraction => `
                    <div class="attraction-item" data-attraction-id="${attraction.id}">
                        <div class="attraction-header">
                            <h5 class="attraction-name">${attraction.name}</h5>
                            <span class="attraction-rating">⭐ ${attraction.rating}</span>
                        </div>
                        <p class="attraction-description">${attraction.description}</p>
                        <div class="attraction-meta">
                            <span>📍 ${attraction.category}</span>
                            <span>⏱️ ${attraction.estimatedTime}</span>
                            <span>💰 ${attraction.ticketPrice}</span>
                        </div>
                    </div>
                `).join('');
            } else {
                attractionsHTML = '<p style="text-align: center; color: #6b7280;">暂无景点数据</p>';
            }
            
            attractionsListEl.innerHTML = attractionsHTML;
            resultsEl.style.display = 'block';
            
            // 滚动到结果区域
            resultsEl.scrollIntoView({ behavior: 'smooth' });
        }
        
        // 显示旅游地图
        function showTravelMap() {
            if (!currentTravelGuide) {
                alert('请先生成旅游导航图！');
                return;
            }
            
            const modal = document.getElementById('travel-map-modal');
            const overlay = document.getElementById('travel-map-overlay');
            
            if (modal && overlay) {
                modal.style.display = 'block';
                overlay.style.display = 'block';
                
                // 初始化地图
                initializeTravelMap();
            }
        }
        
        // 关闭旅游地图
        function closeTravelMap() {
            const modal = document.getElementById('travel-map-modal');
            const overlay = document.getElementById('travel-map-overlay');
            
            if (modal && overlay) {
                modal.style.display = 'none';
                overlay.style.display = 'none';
            }
        }
        
        // 初始化旅游地图
        function initializeTravelMap() {
            const container = document.getElementById('travel-map-container');
            const loading = document.getElementById('travel-map-loading');
            
            if (!container || !currentTravelGuide) return;
            
            // 显示加载状态
            if (loading) loading.style.display = 'block';
            
            // 模拟地图加载
            setTimeout(() => {
                if (loading) loading.style.display = 'none';
                
                // 创建简单的地图展示
                const mapHTML = `
                    <div style="padding: 20px; text-align: center; color: #4a5568;">
                        <h4>🗺️ 旅游路线地图</h4>
                        <div style="background: #f8fafc; border-radius: 10px; padding: 20px; margin: 20px 0; border: 2px dashed #cbd5e0;">
                            <p style="font-size: 16px; margin-bottom: 15px;">📍 ${currentTravelGuide.attractions.length} 个推荐景点</p>
                            <div style="display: grid; gap: 10px;">
                                ${currentTravelGuide.attractions.map((attraction, index) => `
                                    <div style="background: white; padding: 10px; border-radius: 8px; text-align: left; border: 1px solid #e2e8f0;">
                                        <strong>${index + 1}. ${attraction.name}</strong>
                                        <br><small style="color: #6b7280;">${attraction.category} • ${attraction.estimatedTime}</small>
                                    </div>
                                `).join('')}
                            </div>
                            <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #e2e8f0;">
                                <p><strong>总路程:</strong> ${currentTravelGuide.route?.totalDistance || '约15公里'}</p>
                                <p><strong>预计时长:</strong> ${currentTravelGuide.route?.estimatedDuration || '1天'}</p>
                                <p><strong>交通方式:</strong> ${currentTravelGuide.route?.transportation || '地铁+步行'}</p>
                            </div>
                        </div>
                        <p style="color: #9ca3af; font-size: 14px;">💡 完整的交互式地图功能正在开发中</p>
                    </div>
                `;
                
                container.innerHTML = mapHTML;
            }, 1000);
        }
        
        // 导出旅游导航
        function exportTravelGuide() {
            if (!currentTravelGuide) {
                alert('请先生成旅游导航图！');
                return;
            }
            
            // 生成导出内容
            let exportContent = `# ${currentTravelGuide.title}\n\n`;
            exportContent += `${currentTravelGuide.summary}\n\n`;
            exportContent += `## 推荐景点\n\n`;
            
            currentTravelGuide.attractions.forEach((attraction, index) => {
                exportContent += `### ${index + 1}. ${attraction.name}\n`;
                exportContent += `- **评分:** ${attraction.rating}/5.0\n`;
                exportContent += `- **类型:** ${attraction.category}\n`;
                exportContent += `- **游玩时长:** ${attraction.estimatedTime}\n`;
                exportContent += `- **门票:** ${attraction.ticketPrice}\n`;
                exportContent += `- **介绍:** ${attraction.description}\n\n`;
            });
            
            exportContent += `## 路线信息\n\n`;
            exportContent += `- **总路程:** ${currentTravelGuide.route?.totalDistance || '约15公里'}\n`;
            exportContent += `- **预计时长:** ${currentTravelGuide.route?.estimatedDuration || '1天'}\n`;
            exportContent += `- **交通方式:** ${currentTravelGuide.route?.transportation || '地铁+步行'}\n\n`;
            exportContent += `---\n生成时间: ${new Date().toLocaleString()}\n`;
            exportContent += `来源: spot.gitagent.io`;
            
            // 创建下载链接
            const blob = new Blob([exportContent], { type: 'text/markdown;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `旅游导航图_${new Date().toISOString().slice(0, 10)}.md`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            console.log('旅游导航已导出');
        }
        
        // 页面加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定字符计数事件
            const travelPrompt = document.getElementById('travel-prompt');
            if (travelPrompt) {
                travelPrompt.addEventListener('input', updateCharCount);
            }
        });
    </script>
</head>
<body>
    <div class="app-container">
        <!-- 头部导航 -->
        <header class="header">
            <div class="header-left">
                <h1 id="app-title">
                    <span class="compass-logo"></span>
                    <span class="app-title-text">spot.gitagent.io</span>
                </h1>
                <span id="app-subtitle" class="subtitle">Discover your next spot!</span>
            </div>
            <div class="header-right">
                <!-- 语言选择器 -->
                <div class="language-selector">
                    <button class="language-button" onclick="toggleLanguageDropdown()">
                        <span id="current-flag">🇨🇳</span>
                        <span id="current-lang">中文</span>
                    </button>
                    <div class="language-dropdown hidden" id="language-dropdown">
                        <!-- 语言选项将通过JavaScript动态生成 -->
                    </div>
                </div>
                
                <!-- 用户菜单 -->
                <div class="user-menu" id="user-menu">
                    <button class="user-button" onclick="toggleUserMenu()">
                        <div class="user-avatar-container" id="user-avatar-container">
                            <div class="user-avatar" id="user-avatar">👤</div>
                        </div>
                    </button>
                    <div class="user-dropdown hidden" id="user-dropdown">
                        <div class="user-info">
                            <div id="user-email">未登录</div>
                        </div>
                        <div class="user-actions">
                            <button onclick="showAuthModal('login')" id="login-btn">登录</button>
                            <button onclick="showAuthModal('register')" id="register-btn">注册</button>
                            <button onclick="logout()" id="logout-btn" class="hidden">退出登录</button>
                        </div>
                    </div>
                </div>
                
            </div>
        </header>
        
        <!-- 导航控制栏 -->
        <div class="navigation-control-bar">
            <button class="travel-guide-toggle-btn" onclick="toggleTravelGuide()" title="一句话生成导航">
                ✨ <span id="travel-guide-toggle-text">隐藏生成导航</span>
            </button>
            <button class="navigation-toggle-btn" onclick="toggleNavigationPanel()" title="地图景点导航">
                🗺️ <span id="navigation-toggle-text">隐藏导航面板</span>
            </button>
        </div>

        <!-- 导航面板 -->
        <div class="navigation-panel show" id="navigationPanel">
            <!-- 一句话生成旅游导航图功能 -->
            <div class="travel-guide-generator" id="travelGuideGenerator">
                <h3 class="generator-title">🗺️ <span id="travel-guide-title">一句话生成旅游导航图</span></h3>
                <div class="generator-input-section">
                    <div class="input-group">
                        <textarea 
                            id="travel-prompt" 
                            placeholder="例如：我想在北京游玩3天，喜欢历史文化和美食，预算3000元..."
                            rows="3"
                            maxlength="500"
                        ></textarea>
                        <div class="input-counter">
                            <span id="char-count">0</span>/500
                        </div>
                    </div>
                    <div class="generator-actions">
                        <button class="generate-guide-btn" onclick="requireLogin(generateTravelGuide)" id="generate-guide-btn">
                            ✨ <span id="generate-guide-text">生成导航图</span>
                        </button>
                        <button class="clear-prompt-btn" onclick="clearTravelPrompt()" id="clear-prompt-btn">
                            🗑️ <span id="clear-prompt-text">清空</span>
                        </button>
                    </div>
                </div>
                
                <!-- 生成结果展示区域 -->
                <div class="travel-guide-results" id="travel-guide-results" style="display: none;">
                    <div class="results-header">
                        <h4 id="results-title">🎯 生成的旅游导航图</h4>
                        <div class="results-actions">
                            <button class="view-map-btn" onclick="showTravelMap()" id="view-map-btn">
                                🗺️ <span id="view-map-text">查看地图</span>
                            </button>
                            <button class="export-guide-btn" onclick="exportTravelGuide()" id="export-guide-btn">
                                📄 <span id="export-guide-text">导出行程</span>
                            </button>
                        </div>
                    </div>
                    <div class="attractions-list" id="attractions-list">
                        <!-- 动态生成的景点列表 -->
                    </div>
                </div>
                
                <!-- 加载状态 -->
                <div class="guide-loading" id="guide-loading" style="display: none;">
                    <div class="loading-content">
                        <div class="guide-spinner"></div>
                        <h4 class="loading-title">🤖 AI正在为您规划旅程...</h4>
                        <p class="loading-hint">正在分析您的需求并搜索最佳景点 ⏰</p>
                    </div>
                </div>
            </div>
            
            <div class="panel-divider"></div>
            
            <!-- 可折叠的导航设置区域 -->
            <div class="collapsible-navigation-settings" id="collapsibleNavigationSettings">
                <div class="navigation-settings">
                    <h3 class="settings-title">⚙️ <span id="navigation-settings-title">导航设置</span></h3>
                    <div class="setting-group">
                        <label>目标距离:</label>
                        <select id="segmentDistance" onchange="updateSettings()">
                            <option value="5">5km</option>
                            <option value="10" selected>10km</option>
                            <option value="15">15km</option>
                            <option value="20">20km</option>
                        </select>
                    </div>
                <div class="setting-group">
                    <label>模式:</label>
                    <select id="timeMode" onchange="updateSettings()">
                        <option value="present" selected>现代模式</option>
                        <option value="past">古代模式</option>
                    </select>
                </div>

                <div class="setting-group">
                    <label>速度 (km/h):</label>
                    <input type="number" id="speed" value="120" min="1" max="1000" onchange="updateSettings()">
                </div>

                <!-- 城市漫游功能 -->
                <div class="setting-group roaming-section">
                    <label class="roaming-title" id="cityRoamingTitle">🌍 城市漫游:</label>
                
                <!-- 城市选择器 -->
                <div class="city-selector">
                    <div class="input-row">
                        <label id="selectCityLabel">选择城市:</label>
                        <select id="citySelector" class="city-select" onchange="onCitySelected()">
                            <option value="" id="pleaseSelectCityOption">-- 请选择城市 --</option>
                            <optgroup label="🌍 全球知名城市" id="globalCitiesGroup">
                                <!-- 全球城市选项将通过JavaScript动态加载 -->
                            </optgroup>
                            <optgroup label="🇨🇳 中国知名城市" id="chinaCitiesGroup">
                                <!-- 中国城市选项将通过JavaScript动态加载 -->
                            </optgroup>
                        </select>
                    </div>
                    
                    <!-- 城市搜索 -->
                    <div class="input-row">
                        <label id="searchCityLabel">搜索城市:</label>
                        <input type="text" id="citySearch" placeholder="输入城市名称搜索..." class="roaming-input" 
                               oninput="searchCities()" onkeypress="handleSearchEnter(event)">
                    </div>
                    
                    <!-- 搜索结果 -->
                    <div class="search-results" id="searchResults" style="display: none;"></div>
                    
                    <!-- 选中的城市信息 -->
                    <div class="selected-city-info" id="selectedCityInfo" style="display: none;">
                        <div class="city-info-card">
                            <h4 id="selectedCityName"></h4>
                            <p id="selectedCityDetails"></p>
                            <div class="city-actions">
                                <button class="action-btn" onclick="showCityAttractions()" id="viewAttractionsBtn">🏛️ <span id="viewAttractionsText">查看景点</span></button>
                                <button class="action-btn primary" onclick="roamToRandomAttraction()" id="randomRoamingBtn">🎲 <span id="randomRoamingText">随机漫游</span></button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="roaming-status" id="roamingStatus" style="display: none;">
                    <div class="loading-spinner"></div>
                    <span id="roamingStatusText">正在加载城市信息...</span>
                </div>
                </div>
            </div>
        </div>

        <!-- 旅游地图模态框 -->
        <div class="travel-map-modal" id="travel-map-modal" style="display: none;">
            <div class="travel-map-modal-content">
                <div class="travel-map-header">
                    <h3 id="travel-map-title">🗺️ 旅游导航地图</h3>
                    <button class="close-travel-map-btn" onclick="closeTravelMap()">✕</button>
                </div>
                <div class="travel-map-container" id="travel-map-container">
                    <div class="travel-map-loading" id="travel-map-loading">
                        <div class="map-spinner"></div>
                        <p>正在加载地图...</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 旅游地图遮罩层 -->
        <div class="travel-map-overlay" id="travel-map-overlay" style="display: none;" onclick="closeTravelMap()"></div>

        <!-- 状态显示区 -->
        <div class="status-section">
            <div class="location-info">
                <div class="current-location">
                    <span class="label" id="currentLocationLabel">当前位置:</span>
                    <span id="currentLocation">获取中...</span>
                </div>
                <div class="coordinates-info">
                    <span class="label" id="coordinatesLabel">经纬度:</span>
                    <span id="coordinates">--°, --°</span>
                </div>
                <div class="accuracy-info">
                    <span class="label" id="accuracyLabel">精度:</span>
                    <span id="accuracy">--m</span>
                </div>
                <div class="compass-info">
                    <span class="label" id="compassDirectionLabel">朝向:</span>
                    <span id="compassDirection">--°</span>
                </div>
                <div class="direction-text">
                    <span class="label" id="directionTextLabel">方向:</span>
                    <span id="directionText">--</span>
                </div>
            </div>
            
            <!-- 指南针显示 -->
            <div class="compass-container">
                <div class="compass" id="compass">
                    <div class="compass-needle" id="compassNeedle">
                        <div class="needle-diamond">
                            <div class="needle-north"></div>
                            <div class="needle-south"></div>
                        </div>
                    </div>
                    <div class="compass-center"></div>
                    <div class="compass-directions">
                        <div class="direction north">N</div>
                        <div class="direction east">E</div>
                        <div class="direction south">S</div>
                        <div class="direction west">W</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 控制按钮 -->
        <div class="controls">
            <button class="explore-btn" id="exploreBtn" onclick="startExploration()">
                🚀 <span id="startExplorationText">开始探索</span>
            </button>
            <button class="refresh-btn" onclick="refreshLocation()">
                📍 <span id="refreshLocationText">刷新位置</span>
            </button>
            <button class="end-journey-btn" id="endJourneyBtn" onclick="endJourney()" style="display: none;">
                🏠 <span id="endJourneyText">结束旅程</span>
            </button>
        </div>

        <!-- 历史访问场景 -->
        <div class="journey-history-section" id="journeyHistorySection" style="display: none;">
            <h3>🎒 <span id="visitedPlacesText">已访问的地点</span></h3>
            <div class="history-places-container" id="historyPlacesContainer">
                <!-- 历史访问的地点卡片将在这里显示 -->
            </div>
        </div>

        <!-- 地点卡片容器 -->
        <div class="places-container" id="placesContainer">
            <!-- 地点卡片将在这里动态生成 -->
        </div>

        <!-- 加载指示器 -->
        <div class="loading" id="loading" style="display: none;">
            <div class="spinner"></div>
            <p>正在计算路径...</p>
        </div>

        <!-- 日志显示区 -->
        <div class="log-section">
            <div class="log-header">
                <h3 id="systemLogText">系统日志</h3>
                <button class="clear-log-btn" onclick="clearLogs()" id="clearLogsBtn">清空日志</button>
            </div>
            <div class="log-container" id="logContainer">
                <!-- 日志信息将在这里显示 -->
            </div>
        </div>

        <!-- Google街景模态框 -->
        <div class="streetview-modal" id="streetviewModal" style="display: none;">
            <div class="streetview-modal-content">
                <div class="streetview-header">
                    <h3 id="streetviewTitle">🏙️ 街景视图</h3>
                    <button class="close-streetview-btn" onclick="closeStreetView()">✕</button>
                </div>
                <div class="streetview-controls">
                    <button class="streetview-control-btn" onclick="resetStreetViewHeading()" title="重置朝向">
                        🧭 重置视角
                    </button>
                    <button class="streetview-control-btn" onclick="toggleStreetViewFullscreen()" title="全屏">
                        🔍 全屏
                    </button>
                    <button class="streetview-control-btn" onclick="shareStreetView()" title="分享位置">
                        📤 分享
                    </button>
                </div>
                <div class="streetview-container" id="streetviewContainer">
                    <div class="streetview-loading" id="streetviewLoading">
                        <div class="streetview-spinner"></div>
                        <p>正在加载街景...</p>
                    </div>
                    <div class="streetview-error" id="streetviewError" style="display: none;">
                        <div class="error-icon">🚫</div>
                        <h4>街景不可用</h4>
                        <p id="streetviewErrorText">该位置暂时没有街景数据</p>
                        <button class="retry-streetview-btn" onclick="retryStreetView()">重试</button>
                    </div>
                </div>
                <div class="streetview-info" id="streetviewInfo">
                    <div class="streetview-location">
                        <span class="info-label">📍 位置:</span>
                        <span id="streetviewLocation">--</span>
                    </div>
                    <div class="streetview-coordinates">
                        <span class="info-label">📊 坐标:</span>
                        <span id="streetviewCoords">--</span>
                    </div>
                    <div class="streetview-date">
                        <span class="info-label">📅 拍摄时间:</span>
                        <span id="streetviewDate">--</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Google街景遮罩层 -->
        <div class="streetview-overlay" id="streetviewOverlay" style="display: none;" onclick="closeStreetView()"></div>
        
        <!-- 景点合影生成模态框 -->
        <div class="selfie-modal" id="selfieModal" style="display: none;">
            <div class="selfie-modal-content">
                <button class="selfie-close-btn" onclick="closeSelfieModal()" title="关闭">
                    ✕
                </button>
                <div class="selfie-header">
                    <h3>📸 生成景点合影</h3>
                </div>
                
                <div class="selfie-body">
                    <div class="selfie-info">
                        <h4 id="selfieAttractionName">景点名称</h4>
                        <p id="selfieAttractionLocation">位置信息</p>
                    </div>
                    
                    <div class="selfie-upload-section" id="selfieUploadSection">
                        <div class="upload-section">
                            <div class="upload-group">
                                <h4>📷 您的照片</h4>
                                <div class="upload-area" id="uploadArea" onclick="document.getElementById('selfiePhotoInput').click()">
                                    <input type="file" id="selfiePhotoInput" accept="image/*" style="display: none;" onchange="handlePhotoUpload(event)">
                                    <div class="upload-placeholder" id="uploadPlaceholder">
                                        <div class="upload-icon">📷</div>
                                        <p>点击上传您的照片</p>
                                        <p class="upload-hint">支持 JPG、PNG 格式</p>
                                    </div>
                                    <img id="uploadPreview" class="upload-preview" style="display: none;" alt="预览图">
                                </div>
                            </div>
                            
                            <div class="upload-group">
                                <h4>🎨 范例风格图片（可选）</h4>
                                <div class="upload-area" id="styleUploadArea" onclick="document.getElementById('stylePhotoInput').click()">
                                    <input type="file" id="stylePhotoInput" accept="image/*" style="display: none;" onchange="handleStylePhotoUpload(event)">
                                    <div class="upload-placeholder" id="stylePlaceholder">
                                        <div class="upload-icon">🎨</div>
                                        <p>点击上传范例风格图片</p>
                                        <p class="upload-hint">用于模仿服装或风格</p>
                                    </div>
                                    <img id="stylePreview" class="upload-preview" style="display: none;" alt="风格预览图">
                                </div>
                            </div>
                        </div>
                        
                        <div class="prompt-section">
                            <label for="customPrompt">自定义提示词（可选）：</label>
                            <textarea id="customPrompt" rows="3" placeholder="输入额外要求，将追加到基础提示词后面。例如：按第二个橙色高子男生，换他的衣服和裤子服装，头像更换成当前主人的头像，只保留一个人"></textarea>
                        </div>
                        
                        <div class="selfie-actions">
                            <button class="generate-btn" id="generateBtn" onclick="generateSelfie()" disabled>
                                ✨ 生成合影
                            </button>
                            <button class="cancel-btn" onclick="closeSelfieModal()">
                                ❌ 取消
                            </button>
                        </div>
                    </div>
                    
                    <div class="selfie-loading" id="selfieLoading" style="display: none;">
                        <div class="loading-content">
                            <div class="selfie-spinner"></div>
                            <h4 class="loading-title">正在生成您的景点合影...</h4>
                            <p class="loading-hint">这可能需要 10-30 秒，请耐心等待 ⏰</p>
                        </div>
                    </div>
                    
                    <div class="selfie-result" id="selfieResult" style="display: none;">
                        <div class="generated-image-container">
                            <img id="generatedSelfie" class="generated-selfie" alt="生成的合影" onclick="showImageModal(this.src)">
                            <div class="image-hint">点击图片查看大图</div>
                        </div>
                        <div class="result-actions">
                            <button class="download-btn" onclick="downloadSelfie()">
                                💾 下载合影
                            </button>
                            <button class="regenerate-btn" onclick="regenerateWithCurrentStyle()">
                                🔄 当前风格重新生成
                            </button>
                            <button class="share-btn" onclick="shareSelfie()">
                                📤 分享合影
                            </button>
                        </div>
                    </div>
                    
                    <div class="selfie-error" id="selfieError" style="display: none;">
                        <div class="error-icon">❌</div>
                        <h4>生成失败</h4>
                        <p id="selfieErrorMessage">生成合影时出现错误，请重试</p>
                        <button class="retry-btn" onclick="resetSelfieGenerator()">重试</button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 合影生成遮罩层 -->
        <div class="selfie-overlay" id="selfieOverlay" style="display: none;"></div>
        
        <!-- Doro合影生成模态框 -->
        <div class="doro-selfie-modal" id="doroSelfieModal" style="display: none;">
            <div class="doro-modal-content">
                <button class="doro-close-btn" onclick="closeDoroModal()" title="关闭">
                    ✕
                </button>
                <div class="doro-header">
                    <h3>🤝 Doro与我合影</h3>
                    <p class="doro-subtitle">创建您与虚拟伙伴Doro的精彩合影</p>
                </div>
                
                <div class="doro-body">
                    <div class="doro-info">
                        <h4 id="doroAttractionName">景点名称</h4>
                        <p id="doroAttractionLocation">位置信息</p>
                    </div>
                    
                    <!-- 上传区域 -->
                    <div class="upload-section">
                        <div class="upload-group">
                            <h4>📷 您的照片</h4>
                            <div class="upload-area" id="userPhotoArea" onclick="document.getElementById('doroUserPhotoInput').click()">
                                <input type="file" id="doroUserPhotoInput" accept="image/*" style="display: none;" onchange="handleDoroUserPhoto(event)">
                                <div class="upload-placeholder" id="userPhotoPlaceholder">
                                    <div class="upload-icon">📷</div>
                                    <p>点击上传您的照片</p>
                                    <p class="upload-hint">支持 JPG、PNG、WEBP 格式</p>
                                </div>
                                <img id="userPhotoPreview" class="upload-preview" style="display: none;" alt="您的照片">
                            </div>
                        </div>
                        
                        <div class="upload-group">
                            <h4>🎭 选择Doro形象</h4>
                            <div class="doro-selector-container">
                                <div class="doro-selector-tabs">
                                    <button class="doro-tab active" onclick="switchDoroTab('preset')">预设Doro</button>
                                    <button class="doro-tab" onclick="switchDoroTab('custom')">自定义Doro</button>
                                </div>
                                <div class="doro-selector-grid" id="doroSelectorGrid">
                                    <!-- 动态加载Doro列表 -->
                                </div>
                                <div class="doro-upload-custom" id="doroUploadCustom" style="display: none;">
                                    <div class="upload-area" onclick="document.getElementById('doroCustomInput').click()">
                                        <input type="file" id="doroCustomInput" accept="image/*" style="display: none;" onchange="handleCustomDoro(event)">
                                        <div class="upload-placeholder">
                                            <div class="upload-icon">➕</div>
                                            <p>上传自定义Doro形象</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 可选：服装风格参考 -->
                    <div class="upload-section">
                        <div class="upload-group">
                            <h4>👔 服装风格参考（可选）</h4>
                            <div class="upload-area" id="stylePhotoArea" onclick="document.getElementById('doroStyleInput').click()">
                                <input type="file" id="doroStyleInput" accept="image/*" style="display: none;" onchange="handleDoroStylePhoto(event)">
                                <div class="upload-placeholder" id="stylePlaceholder">
                                    <div class="upload-icon">👔</div>
                                    <p>点击上传服装风格参考</p>
                                    <p class="upload-hint">可选：用于统一服装风格</p>
                                </div>
                                <img id="doroStylePreview" class="upload-preview" style="display: none;" alt="风格参考">
                            </div>
                        </div>
                        
                        <div class="upload-group">
                            <h4>✏️ 自定义提示词（可选）</h4>
                            <textarea id="doroCustomPrompt" placeholder="输入额外要求，将追加到基础提示词后面。例如：按第二个橙色高子男生，换他的衣服和裤子服装，头像更换成当前主人的头像，只保留一个人" rows="3"></textarea>
                        </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="doro-actions">
                        <button class="doro-generate-btn" id="doroGenerateBtn" onclick="generateDoroSelfie()" disabled>
                            ✨ 生成Doro合影
                        </button>
                        <button class="doro-video-btn" id="doroVideoBtn" onclick="generateDoroVideo()" disabled>
                            🎬 生成Doro合影视频
                        </button>
                        <button class="doro-cancel-btn" onclick="closeDoroModal()">
                            ❌ 取消
                        </button>
                    </div>

                    
                    <!-- 加载状态 -->
                    <div class="doro-loading" id="doroLoading" style="display: none;">
                        <div class="loading-content">
                            <div class="doro-spinner"></div>
                            <h4 class="loading-title">正在生成Doro合影...</h4>
                            <p class="loading-hint">AI正在将您、Doro和景点完美融合 🎨</p>
                            <p class="loading-hint">预计需要 15-30 秒 ⏰</p>
                        </div>
                    </div>
                    
                    <!-- 结果展示 -->
                    <div class="doro-result" id="doroResult" style="display: none;">
                        <div class="generated-image-container">
                            <img id="generatedDoroSelfie" class="generated-selfie" alt="Doro合影" onclick="showImageModal(this.src)">
                            <div class="image-hint">点击图片查看大图</div>
                        </div>
                        <div class="result-actions">
                            <button class="download-btn" onclick="downloadDoroSelfie()">
                                💾 下载合影
                            </button>
                            <button class="regenerate-btn" onclick="regenerateDoroSelfie()">
                                🔄 重新生成
                            </button>
                            <button class="share-btn" onclick="shareDoroSelfie()">
                                📤 分享合影
                            </button>
                        </div>
                    </div>
                    
                    <!-- 视频结果展示 -->
                    <div class="doro-video-result" id="doroVideoResult" style="display: none;">
                        <div class="generated-video-container">
                            <video id="generatedDoroVideo" class="generated-video" controls>
                                您的浏览器不支持视频播放
                            </video>
                            <div class="video-hint">Doro合影视频已生成</div>
                        </div>
                        <div class="video-result-actions">
                            <button class="download-btn" onclick="downloadDoroVideo()">
                                💾 下载视频
                            </button>
                            <button class="regenerate-btn" onclick="regenerateDoroVideo()">
                                🔄 重新生成视频
                            </button>
                            <button class="share-btn" onclick="shareDoroVideo()">
                                📤 分享视频
                            </button>
                        </div>
                    </div>
                    
                    <!-- 错误提示 -->
                    <div class="doro-error" id="doroError" style="display: none;">
                        <div class="error-icon">🤖💥</div>
                        <h4>AI抛锚了</h4>
                        <p id="doroErrorMessage">这点小故障，你看肿么办？</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Doro合影遮罩层 -->
        <div class="doro-overlay" id="doroOverlay" style="display: none;"></div>
    </div>

    <!-- Google Maps JavaScript API 配置 -->
    <script>
        // API基础URL配置 - 支持环境变量控制
        function getAPIBaseURL() {
            // 检查是否在生产环境（通过域名访问）
            const isProduction = window.location.hostname === 'spot.gitagent.io' ||
                                 window.location.hostname.includes('gitagent.io');
            
            // 检查localStorage中的配置（优先级最高）
            const localStorageConfig = localStorage.getItem('isUsedomainnameaddress');
            
            // 检查URL参数
            const urlHasUseDomain = window.location.search.includes('usedomainname=true');
            const urlHasUseLocal = window.location.search.includes('usedomainname=false');
            
            // 决定使用哪个API URL
            if (localStorageConfig === 'false' && !isProduction) {
                // 明确设置为本地开发
                return 'http://localhost:8001';
            } else if (localStorageConfig === 'true' || urlHasUseDomain || isProduction) {
                // 生产环境或明确设置使用域名
                return 'https://spot.gitagent.io';
            } else if (urlHasUseLocal) {
                // URL参数明确指定使用本地
                return 'http://localhost:8001';
            } else {
                // 默认：如果通过域名访问则使用域名，否则使用本地
                return isProduction ? 'https://spot.gitagent.io' : 'http://localhost:8001';
            }
        }
        
        const API_BASE_URL = getAPIBaseURL();
        window.API_BASE_URL = API_BASE_URL; // 设置为全局变量，供iframe使用
        console.log('🔧 API_BASE_URL配置:', API_BASE_URL);
        
        // 应用配置 - API Key配置在环境变量中
        window.appConfig = {
            // 注意：实际部署时应从后端或环境变量获取此值
            // 不要将真实的API Key提交到代码库！
            // 开发时请在 .env 文件中设置 GOOGLE_MAPS_API_KEY
            googleMapsApiKey: 'AIzaSyC3fc8-5r4SWOISs0IIduiE4TOvE8-aFC0', // 将被动态替换
            useLangchain: true
        };

        // 尝试从后端获取API配置（生产环境推荐）
        async function loadAppConfig() {
            try {
                const response = await fetch(`${API_BASE_URL}/api/config/maps`);
                if (response.ok) {
                    const config = await response.json();
                    window.appConfig.googleMapsApiKey = config.google_maps_api_key;
                    console.log('✅ 从后端获取到API配置');
                }
            } catch (error) {
                console.log('⚠️ 无法从后端获取API配置，使用默认配置');
            }
        }

        // 添加全局状态变量
        window.googleMapsLoadStatus = 'pending'; // pending, loading, loaded, failed

        // Google Maps API 回调函数
        window.initGoogleMaps = function() {
            console.log('✅ Google Maps API 已加载');
            console.log('🏙️ Street View 服务已准备就绪');
            window.googleMapsLoadStatus = 'loaded';

            // 初始化街景相关变量
            if (typeof initGoogleMapsAPI === 'function') {
                initGoogleMapsAPI();
            }
            
            // 触发自定义事件，通知API已加载
            window.dispatchEvent(new Event('googleMapsLoaded'));
        };

        // 动态加载Google Maps API
        function loadGoogleMapsAPI() {
            const apiKey = window.appConfig.googleMapsApiKey;
            
            console.log('🔍 开始加载Google Maps API');
            console.log('   API Key:', apiKey ? apiKey.substring(0, 10) + '...' : '未设置');

            if (!apiKey || apiKey === 'YOUR_GOOGLE_MAPS_API_KEY') {
                console.warn('⚠️ Google Maps API Key 未配置');
                window.googleMapsLoadStatus = 'failed';
                return false;
            }

            // 检查是否已经加载过
            if (window.google && window.google.maps) {
                console.log('✅ Google Maps API 已存在');
                window.googleMapsLoadStatus = 'loaded';
                window.initGoogleMaps();
                return true;
            }

            window.googleMapsLoadStatus = 'loading';
            console.log('🔄 正在加载 Google Maps API...');
            
            const script = document.createElement('script');
            script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=initGoogleMaps&v=weekly&libraries=geometry`;
            script.async = true;
            script.defer = true;
            
            script.onload = function() {
                console.log('✅ Google Maps script标签加载完成');
            };
            
            script.onerror = function(error) {
                window.googleMapsLoadStatus = 'failed';
                console.error('❌ Google Maps API 加载失败');
                console.log('🔍 请检查:');
                console.log('   1. API Key 是否正确');
                console.log('   2. 网络连接是否正常');
                console.log('   3. API Key 是否有正确的权限');
                console.log('   4. 浏览器控制台是否有其他错误');
            };
            
            document.head.appendChild(script);
            return true;
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async function() {
            console.log('🚀 OrientDiscover 应用启动');

            // 初始化Supabase认证监听
            setTimeout(initializeSupabaseAuth, 1000);

            // 先尝试加载配置
            await loadAppConfig();

            // 然后加载Google Maps API
            loadGoogleMapsAPI();
        });
    </script>

    <script src="i18n/index.js"></script>
    <script src="app.js"></script>
    
    <!-- 认证模态框 -->
    <div id="auth-modal" class="auth-modal hidden">
        <div class="auth-modal-content">
            <div class="auth-modal-header">
                <h2 id="modal-title">用户认证</h2>
                <button class="close-btn" onclick="closeAuthModal()">×</button>
            </div>
            <div class="auth-modal-body">
                <iframe src="auth-modal.html?v=20250928" width="100%" height="500" frameborder="0"></iframe>
            </div>
        </div>
    </div>
    
    <script>
        // 多语言和认证相关功能
        // currentLanguage 在 app.js 中已声明
        let currentUser = null;
        
        // 翻译数据
        const translations = {
            zh: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "用户",
                guest: "游客",
                login: "登录",
                register: "注册",
                logout: "退出登录",
                notLoggedIn: "未登录",
                currentLocation: "当前位置",
                nearbyAttractions: "附近景点",
                exploreHere: "漫游到这里",
                generatePhoto: "生成合影",
                viewStreetView: "查看街景",
                doroPhoto: "Doro合影",
                noAttractionsFound: "没有找到相关地点信息",
                searching: "搜索中...",
                loading: "加载中...",
                distance: "距离",
                settings: "设置",
                targetDistance: "目标距离",
                mode: "模式",
                speed: "速度 (km/h)",
                cityRoaming: "城市漫游",
                selectCity: "选择城市",
                modernMode: "现代模式",
                ancientMode: "古代模式",
                futureMode: "未来模式",
                noInfo: "暂无信息",
                coordinates: "经纬度",
                accuracy: "精度",
                compassDirection: "朝向",
                directionText: "方向",
                startExploration: "开始探索",
                refreshLocation: "刷新位置",
                endJourney: "结束旅程",
                visitedPlaces: "已访问的地点",
                systemLog: "系统日志",
                clearLogs: "清空日志",
                viewAttractions: "查看景点",
                randomRoaming: "随机漫游",
                cityRoaming: "城市漫游",
                selectCity: "选择城市",
                searchCity: "搜索城市",
                pleaseSelectCity: "-- 请选择城市 --",
                enterCityName: "输入城市名称搜索...",
                globalCities: "全球知名城市",
                chinaCities: "中国知名城市",
                loadingCityInfo: "正在加载城市信息...",
                streetView: "街景视图",
                resetView: "重置视角",
                fullscreen: "全屏",
                share: "分享",
                loadingStreetView: "正在加载街景...",
                streetViewUnavailable: "街景不可用",
                retry: "重试",
                location: "位置",
                coordinates: "坐标",
                shootingTime: "拍摄时间",
                generateSelfie: "生成景点合影",
                attractionName: "景点名称",
                locationInfo: "位置信息",
                yourPhoto: "您的照片",
                clickToUpload: "点击上传您的照片",
                supportFormats: "支持 JPG、PNG 格式",
                stylePhoto: "范例风格图片（可选）",
                clickToUploadStyle: "点击上传范例风格图片",
                styleHint: "用于模仿服装或风格",
                customPrompt: "自定义提示词（可选）",
                customPromptPlaceholder: "输入额外要求，将追加到基础提示词后面。例如：按第二个橙色高子男生，换他的衣服和裤子服装，头像更换成当前主人的头像，只保留一个人",
                generate: "生成合影",
                cancel: "取消",
                generatingSelfie: "正在生成您的景点合影...",
                generatingHint: "这可能需要 10-30 秒，请耐心等待 ⏰",
                clickImageToView: "点击图片查看大图",
                downloadPhoto: "下载合影",
                regenerateWithStyle: "当前风格重新生成",
                sharePhoto: "分享合影",
                generationFailed: "生成失败",
                generationError: "生成合影时出现错误，请重试",
                doroSelfie: "Doro与我合影",
                doroSubtitle: "创建您与虚拟伙伴Doro的精彩合影",
                selectDoro: "选择Doro形象",
                presetDoro: "预设Doro",
                customDoro: "自定义Doro",
                uploadCustomDoro: "上传自定义Doro形象",
                styleReference: "服装风格参考（可选）",
                clickToUploadStyle: "点击上传服装风格参考",
                styleReferenceHint: "可选：用于统一服装风格",
                customPromptDoro: "自定义提示词（可选）",
                generateDoroSelfie: "生成Doro合影",
                generatingDoroSelfie: "正在生成Doro合影...",
                generatingDoroHint: "AI正在将您、Doro和景点完美融合 🎨",
                generatingDoroTime: "预计需要 15-30 秒 ⏰",
                doroError: "AI抛锚了",
                doroErrorMessage: "这点小故障，你看肿么办？",
                showNavigationPanel: "显示导航面板",
                hideNavigationPanel: "隐藏导航面板",
                showTravelGuide: "显示生成导航",
                hideTravelGuide: "隐藏生成导航",
                navigationPanel: "地图景点导航",
                travelGuideTitle: "一句话生成旅游导航图",
                generateGuideText: "生成导航图",
                clearPromptText: "清空",
                resultsTitle: "生成的旅游导航图",
                viewMapText: "查看地图",
                exportGuideText: "导出行程",
                navigationSettingsTitle: "导航设置",
                travelMapTitle: "旅游导航地图"
            },
            en: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "User",
                guest: "Guest",
                login: "Login",
                register: "Register",
                logout: "Logout",
                notLoggedIn: "Not Logged In",
                currentLocation: "Current Location",
                nearbyAttractions: "Nearby Attractions",
                exploreHere: "Roam to Here",
                generatePhoto: "Generate Photo",
                viewStreetView: "View Street View",
                doroPhoto: "Doro Photo",
                noAttractionsFound: "No relevant location information found",
                searching: "Searching...",
                loading: "Loading...",
                distance: "Distance",
                settings: "Settings",
                targetDistance: "Target Distance",
                mode: "Mode",
                speed: "Speed (km/h)",
                cityRoaming: "City Roaming",
                selectCity: "Select City",
                modernMode: "Modern Mode",
                ancientMode: "Ancient Mode",
                futureMode: "Future Mode",
                noInfo: "No Info",
                coordinates: "Coordinates",
                accuracy: "Accuracy",
                compassDirection: "Heading",
                directionText: "Direction",
                startExploration: "Start Exploration",
                refreshLocation: "Refresh Location",
                endJourney: "End Journey",
                visitedPlaces: "Visited Places",
                systemLog: "System Log",
                clearLogs: "Clear Logs",
                viewAttractions: "View Attractions",
                randomRoaming: "Random Roaming",
                cityRoaming: "City Roaming",
                selectCity: "Select City",
                searchCity: "Search City",
                pleaseSelectCity: "-- Please select city --",
                enterCityName: "Enter city name to search...",
                globalCities: "Global Famous Cities",
                chinaCities: "China Famous Cities",
                loadingCityInfo: "Loading city information...",
                streetView: "Street View",
                resetView: "Reset View",
                fullscreen: "Fullscreen",
                share: "Share",
                loadingStreetView: "Loading Street View...",
                streetViewUnavailable: "Street View Unavailable",
                retry: "Retry",
                location: "Location",
                coordinates: "Coordinates",
                shootingTime: "Shooting Time",
                generateSelfie: "Generate Selfie",
                attractionName: "Attraction Name",
                locationInfo: "Location Info",
                yourPhoto: "Your Photo",
                clickToUpload: "Click to upload your photo",
                supportFormats: "Supports JPG, PNG formats",
                stylePhoto: "Style Reference Photo (Optional)",
                clickToUploadStyle: "Click to upload style reference",
                styleHint: "For imitating clothing or style",
                customPrompt: "Custom Prompt (Optional)",
                customPromptPlaceholder: "Enter additional requirements to append to the base prompt. For example: Follow the second orange tall boy, change his clothes and pants, replace the head with the current owner's head, keep only one person",
                generate: "Generate Photo",
                cancel: "Cancel",
                generatingSelfie: "Generating your attraction selfie...",
                generatingHint: "This may take 10-30 seconds, please be patient ⏰",
                clickImageToView: "Click image to view full size",
                downloadPhoto: "Download Photo",
                regenerateWithStyle: "Regenerate with Current Style",
                sharePhoto: "Share Photo",
                generationFailed: "Generation Failed",
                generationError: "Error generating selfie, please try again",
                doroSelfie: "Doro & Me Selfie",
                doroSubtitle: "Create amazing selfies with your virtual companion Doro",
                selectDoro: "Select Doro Character",
                presetDoro: "Preset Doro",
                customDoro: "Custom Doro",
                uploadCustomDoro: "Upload Custom Doro Character",
                styleReference: "Clothing Style Reference (Optional)",
                clickToUploadStyle: "Click to upload clothing style reference",
                styleReferenceHint: "Optional: for unified clothing style",
                customPromptDoro: "Custom Prompt (Optional)",
                generateDoroSelfie: "Generate Doro Selfie",
                generatingDoroSelfie: "Generating Doro selfie...",
                generatingDoroHint: "AI is perfectly blending you, Doro and the attraction 🎨",
                generatingDoroTime: "Estimated 15-30 seconds ⏰",
                doroError: "AI Broke Down",
                doroErrorMessage: "This little glitch, what do you think we should do?",
                showNavigationPanel: "Show Navigation Panel",
                hideNavigationPanel: "Hide Navigation Panel",
                navigationPanel: "Map Attractions Navigation",
                travelGuideTitle: "Generate Travel Guide in One Sentence",
                generateGuideText: "Generate Guide",
                clearPromptText: "Clear",
                resultsTitle: "Generated Travel Guide",
                viewMapText: "View Map",
                exportGuideText: "Export Itinerary",
                navigationSettingsTitle: "Navigation Settings",
                travelMapTitle: "Travel Navigation Map"
            },
            es: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Usuario",
                guest: "Invitado",
                login: "Iniciar Sesión",
                register: "Registrarse",
                logout: "Cerrar Sesión",
                notLoggedIn: "No Conectado",
                currentLocation: "Ubicación Actual",
                nearbyAttractions: "Atracciones Cercanas",
                exploreHere: "Explorar Aquí",
                generatePhoto: "Generar Foto",
                viewStreetView: "Ver Vista de Calle",
                doroPhoto: "Foto Doro",
                noAttractionsFound: "No se encontró información de ubicación relevante",
                searching: "Buscando...",
                loading: "Cargando...",
                distance: "Distancia",
                settings: "Configuración",
                targetDistance: "Distancia Objetivo",
                mode: "Modo",
                speed: "Velocidad (km/h)",
                cityRoaming: "Paseo por la Ciudad",
                selectCity: "Seleccionar Ciudad",
                modernMode: "Modo Moderno",
                ancientMode: "Modo Antiguo",
                futureMode: "Modo Futuro",
                noInfo: "Sin Información"
            },
            fr: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Utilisateur",
                guest: "Invité",
                login: "Connexion",
                register: "Inscription",
                logout: "Déconnexion",
                notLoggedIn: "Non Connecté",
                currentLocation: "Localisation Actuelle",
                nearbyAttractions: "Attractions Proches",
                exploreHere: "Explorer Ici",
                generatePhoto: "Générer Photo",
                viewStreetView: "Voir Vue de Rue",
                doroPhoto: "Photo Doro",
                noAttractionsFound: "Aucune information de localisation pertinente trouvée",
                searching: "Recherche...",
                loading: "Chargement...",
                distance: "Distance",
                settings: "Paramètres",
                targetDistance: "Distance Cible",
                mode: "Mode",
                speed: "Vitesse (km/h)",
                cityRoaming: "Promenade Urbaine",
                selectCity: "Sélectionner Ville",
                modernMode: "Mode Moderne",
                ancientMode: "Mode Ancien",
                futureMode: "Mode Futur",
                noInfo: "Aucune Info"
            },
            de: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Benutzer",
                guest: "Gast",
                login: "Anmelden",
                register: "Registrieren",
                logout: "Abmelden",
                notLoggedIn: "Nicht Angemeldet",
                currentLocation: "Aktuelle Position",
                nearbyAttractions: "Nahegelegene Sehenswürdigkeiten",
                exploreHere: "Hier Erkunden",
                generatePhoto: "Foto Generieren",
                viewStreetView: "Straßenansicht Anzeigen",
                doroPhoto: "Doro Foto",
                noAttractionsFound: "Keine relevanten Standortinformationen gefunden",
                searching: "Suche...",
                loading: "Laden...",
                distance: "Entfernung",
                settings: "Einstellungen",
                targetDistance: "Zieldistanz",
                mode: "Modus",
                speed: "Geschwindigkeit (km/h)",
                cityRoaming: "Stadtbummel",
                selectCity: "Stadt Auswählen",
                modernMode: "Moderner Modus",
                ancientMode: "Antiker Modus",
                futureMode: "Zukunftsmodus",
                noInfo: "Keine Info"
            },
            ja: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "ユーザー",
                guest: "ゲスト",
                login: "ログイン",
                register: "新規登録",
                logout: "ログアウト",
                notLoggedIn: "未ログイン",
                currentLocation: "現在地",
                nearbyAttractions: "近くの観光地",
                exploreHere: "ここを探索",
                generatePhoto: "写真を生成",
                viewStreetView: "ストリートビューを見る",
                doroPhoto: "Doro写真",
                noAttractionsFound: "関連する場所情報が見つかりません",
                searching: "検索中...",
                loading: "読み込み中...",
                distance: "距離",
                settings: "設定",
                targetDistance: "目標距離",
                mode: "モード",
                speed: "速度 (km/h)",
                cityRoaming: "街歩き",
                selectCity: "都市を選択",
                modernMode: "モダンモード",
                ancientMode: "古代モード",
                futureMode: "未来モード",
                noInfo: "情報なし"
            },
            ko: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "사용자",
                guest: "게스트",
                login: "로그인",
                register: "회원가입",
                logout: "로그아웃",
                notLoggedIn: "로그인 안됨",
                currentLocation: "현재 위치",
                nearbyAttractions: "주변 관광지",
                exploreHere: "여기 탐험하기",
                generatePhoto: "사진 생성",
                viewStreetView: "스트리트뷰 보기",
                doroPhoto: "Doro 사진",
                noAttractionsFound: "관련 위치 정보를 찾을 수 없습니다",
                searching: "검색 중...",
                loading: "로딩 중...",
                distance: "거리",
                settings: "설정",
                targetDistance: "목표 거리",
                mode: "모드",
                speed: "속도 (km/h)",
                cityRoaming: "도시 산책",
                selectCity: "도시 선택",
                modernMode: "모던 모드",
                ancientMode: "고대 모드",
                futureMode: "미래 모드",
                noInfo: "정보 없음"
            },
            it: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Utente",
                guest: "Ospite",
                login: "Accedi",
                register: "Registrati",
                logout: "Disconnetti",
                notLoggedIn: "Non Connesso",
                currentLocation: "Posizione Attuale",
                nearbyAttractions: "Attrazioni Vicine",
                exploreHere: "Esplora Qui",
                generatePhoto: "Genera Foto",
                viewStreetView: "Visualizza Street View",
                doroPhoto: "Foto Doro",
                noAttractionsFound: "Nessuna informazione di posizione rilevante trovata",
                searching: "Ricerca...",
                loading: "Caricamento...",
                distance: "Distanza",
                settings: "Impostazioni",
                targetDistance: "Distanza Obiettivo",
                mode: "Modalità",
                speed: "Velocità (km/h)",
                cityRoaming: "Passeggiata in Città",
                selectCity: "Seleziona Città",
                modernMode: "Modalità Moderna",
                ancientMode: "Modalità Antica",
                futureMode: "Modalità Futura",
                noInfo: "Nessuna Info"
            },
            pt: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Usuário",
                guest: "Convidado",
                login: "Entrar",
                register: "Registrar",
                logout: "Sair",
                notLoggedIn: "Não Conectado",
                currentLocation: "Localização Atual",
                nearbyAttractions: "Atrações Próximas",
                exploreHere: "Explorar Aqui",
                generatePhoto: "Gerar Foto",
                viewStreetView: "Ver Vista de Rua",
                doroPhoto: "Foto Doro",
                noAttractionsFound: "Nenhuma informação de localização relevante encontrada",
                searching: "Pesquisando...",
                loading: "Carregando...",
                distance: "Distância",
                settings: "Configurações",
                targetDistance: "Distância Alvo",
                mode: "Modo",
                speed: "Velocidade (km/h)",
                cityRoaming: "Passeio pela Cidade",
                selectCity: "Selecionar Cidade",
                modernMode: "Modo Moderno",
                ancientMode: "Modo Antigo",
                futureMode: "Modo Futuro",
                noInfo: "Sem Informação"
            },
            ru: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Пользователь",
                guest: "Гость",
                login: "Войти",
                register: "Регистрация",
                logout: "Выйти",
                notLoggedIn: "Не Войден",
                currentLocation: "Текущее Местоположение",
                nearbyAttractions: "Близлежащие Достопримечательности",
                exploreHere: "Исследовать Здесь",
                generatePhoto: "Создать Фото",
                viewStreetView: "Посмотреть Панораму",
                doroPhoto: "Фото Доро",
                noAttractionsFound: "Не найдено релевантной информации о местоположении",
                searching: "Поиск...",
                loading: "Загрузка...",
                distance: "Расстояние",
                settings: "Настройки",
                targetDistance: "Целевое Расстояние",
                mode: "Режим",
                speed: "Скорость (км/ч)",
                cityRoaming: "Городская Прогулка",
                selectCity: "Выбрать Город",
                modernMode: "Современный Режим",
                ancientMode: "Древний Режим",
                futureMode: "Будущий Режим",
                noInfo: "Нет Информации"
            },
            ar: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "المستخدم",
                guest: "ضيف",
                login: "تسجيل الدخول",
                register: "التسجيل",
                logout: "تسجيل الخروج",
                notLoggedIn: "غير مسجل الدخول",
                currentLocation: "الموقع الحالي",
                nearbyAttractions: "المعالم القريبة",
                exploreHere: "استكشف هنا",
                generatePhoto: "إنشاء صورة",
                viewStreetView: "عرض الشارع",
                doroPhoto: "صورة دورو",
                noAttractionsFound: "لم يتم العثور على معلومات موقع ذات صلة",
                searching: "جاري البحث...",
                loading: "جاري التحميل...",
                distance: "المسافة",
                settings: "الإعدادات",
                targetDistance: "المسافة المستهدفة",
                mode: "الوضع",
                speed: "السرعة (كم/ساعة)",
                cityRoaming: "تجول في المدينة",
                selectCity: "اختر المدينة",
                modernMode: "الوضع الحديث",
                ancientMode: "الوضع القديم",
                futureMode: "وضع المستقبل",
                noInfo: "لا توجد معلومات"
            },
            hi: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "उपयोगकर्ता",
                guest: "अतिथि",
                login: "लॉग इन",
                register: "रजिस्टर",
                logout: "लॉग आउट",
                notLoggedIn: "लॉग इन नहीं",
                currentLocation: "वर्तमान स्थान",
                nearbyAttractions: "पास के आकर्षण",
                exploreHere: "यहाँ अन्वेषण करें",
                generatePhoto: "फोटो बनाएं",
                viewStreetView: "स्ट्रीट व्यू देखें",
                doroPhoto: "डोरो फोटो",
                noAttractionsFound: "संबंधित स्थान जानकारी नहीं मिली",
                searching: "खोज रहे हैं...",
                loading: "लोड हो रहा है...",
                distance: "दूरी",
                settings: "सेटिंग्स",
                targetDistance: "लक्ष्य दूरी",
                mode: "मोड",
                speed: "गति (किमी/घंटा)",
                cityRoaming: "शहर भ्रमण",
                selectCity: "शहर चुनें",
                modernMode: "आधुनिक मोड",
                ancientMode: "प्राचीन मोड",
                futureMode: "भविष्य मोड",
                noInfo: "कोई जानकारी नहीं"
            },
            tr: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Kullanıcı",
                guest: "Misafir",
                login: "Giriş Yap",
                register: "Kayıt Ol",
                logout: "Çıkış Yap",
                notLoggedIn: "Giriş Yapılmamış",
                currentLocation: "Mevcut Konum",
                nearbyAttractions: "Yakındaki Turistik Yerler",
                exploreHere: "Burayı Keşfet",
                generatePhoto: "Fotoğraf Oluştur",
                viewStreetView: "Sokak Görünümünü Görüntüle",
                doroPhoto: "Doro Fotoğrafı",
                noAttractionsFound: "İlgili konum bilgisi bulunamadı",
                searching: "Aranıyor...",
                loading: "Yükleniyor...",
                distance: "Mesafe",
                settings: "Ayarlar",
                targetDistance: "Hedef Mesafe",
                mode: "Mod",
                speed: "Hız (km/saat)",
                cityRoaming: "Şehir Gezisi",
                selectCity: "Şehir Seç",
                modernMode: "Modern Mod",
                ancientMode: "Antik Mod",
                futureMode: "Gelecek Modu",
                noInfo: "Bilgi Yok"
            },
            nl: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Gebruiker",
                guest: "Gast",
                login: "Inloggen",
                register: "Registreren",
                logout: "Uitloggen",
                notLoggedIn: "Niet Ingelogd",
                currentLocation: "Huidige Locatie",
                nearbyAttractions: "Nabijgelegen Bezienswaardigheden",
                exploreHere: "Verken Hier",
                generatePhoto: "Foto Genereren",
                viewStreetView: "Straatweergave Bekijken",
                doroPhoto: "Doro Foto",
                noAttractionsFound: "Geen relevante locatie-informatie gevonden",
                searching: "Zoeken...",
                loading: "Laden...",
                distance: "Afstand",
                settings: "Instellingen",
                targetDistance: "Doelafstand",
                mode: "Modus",
                speed: "Snelheid (km/h)",
                cityRoaming: "Stadswandeling",
                selectCity: "Stad Selecteren",
                modernMode: "Moderne Modus",
                ancientMode: "Oude Modus",
                futureMode: "Toekomst Modus",
                noInfo: "Geen Info"
            },
            he: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "משתמש",
                guest: "אורח",
                login: "התחבר",
                register: "הירשם",
                logout: "התנתק",
                notLoggedIn: "לא מחובר",
                currentLocation: "מיקום נוכחי",
                nearbyAttractions: "אטרקציות קרובות",
                exploreHere: "חקור כאן",
                generatePhoto: "צור תמונה",
                viewStreetView: "הצג תצוגת רחוב",
                doroPhoto: "תמונת דורו",
                noAttractionsFound: "לא נמצא מידע מיקום רלוונטי",
                searching: "מחפש...",
                loading: "טוען...",
                distance: "מרחק",
                settings: "הגדרות",
                targetDistance: "מרחק יעד",
                mode: "מצב",
                speed: "מהירות (קמ/ש)",
                cityRoaming: "טיול עירוני",
                selectCity: "בחר עיר",
                modernMode: "מצב מודרני",
                ancientMode: "מצב עתיק",
                futureMode: "מצב עתיד",
                noInfo: "אין מידע"
            },
            bg: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                user: "Потребител",
                guest: "Гост",
                login: "Вход",
                register: "Регистрация",
                logout: "Изход",
                notLoggedIn: "Не е влязъл",
                currentLocation: "Текущо местоположение",
                nearbyAttractions: "Близки забележителности",
                exploreHere: "Изследвай тук",
                generatePhoto: "Генерирай снимка",
                viewStreetView: "Виж уличен изглед",
                doroPhoto: "Доро снимка",
                noAttractionsFound: "Не е намерена релевантна информация за местоположение",
                searching: "Търсене...",
                loading: "Зареждане...",
                distance: "Разстояние",
                settings: "Настройки",
                targetDistance: "Целево разстояние",
                mode: "Режим",
                speed: "Скорост (км/ч)",
                cityRoaming: "Градска Разходка",
                selectCity: "Избери Град",
                modernMode: "Модерен Режим",
                ancientMode: "Древен Режим",
                futureMode: "Бъдещ Режим",
                noInfo: "Няма Информация"
            }
        };
        
        // 设置翻译
        window.translations = translations;
        

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeLanguage();
            checkAuthStatus();
            setupAuthEventListeners();
        });

        function initializeLanguage() {
            currentLanguage = i18n.getCurrentLanguage();
            // 设置为全局变量，供iframe访问
            window.currentLanguage = currentLanguage;
            updateLanguageUI();
            generateLanguageOptions();
            updateLanguageButton();
        }
        
        function updateLanguageUI() {
            const t = translations[currentLanguage] || translations['zh'];
            
            // 更新页面元素
            document.getElementById('app-title').textContent = t.appTitle;
            document.getElementById('app-subtitle').textContent = t.appSubtitle;
            // 更新用户头像提示
            const userAvatarEl = document.getElementById('user-avatar');
            if (userAvatarEl && currentUser) {
                userAvatarEl.title = `${currentUser.username} (已登录)`;
            } else if (userAvatarEl) {
                userAvatarEl.title = t.guest || '游客 (点击登录)';
            }
            document.getElementById('login-btn').textContent = t.login;
            document.getElementById('register-btn').textContent = t.register;
            document.getElementById('logout-btn').textContent = t.logout;
            
            // 更新其他页面元素
            updatePageContent(t);
        }
        
        function updatePageContent(t) {
            // 更新设置面板
            const labels = document.querySelectorAll('.setting-group label');
            if (labels[0]) labels[0].textContent = t.targetDistance + ':';
            if (labels[1]) labels[1].textContent = t.mode + ':';
            if (labels[2]) labels[2].textContent = t.speed + ':';
            
            // 更新选项文本
            const options = document.querySelectorAll('option');
            options.forEach(option => {
                if (option.value === 'present') option.textContent = t.modernMode;
                if (option.value === 'past') option.textContent = t.ancientMode;
            });
            
            // 更新状态显示区标签
            const currentLocationLabel = document.getElementById('currentLocationLabel');
            const coordinatesLabel = document.getElementById('coordinatesLabel');
            const accuracyLabel = document.getElementById('accuracyLabel');
            const compassDirectionLabel = document.getElementById('compassDirectionLabel');
            const directionTextLabel = document.getElementById('directionTextLabel');
            
            if (currentLocationLabel) currentLocationLabel.textContent = t.currentLocation + ':';
            if (coordinatesLabel) coordinatesLabel.textContent = t.coordinates + ':';
            if (accuracyLabel) accuracyLabel.textContent = t.accuracy + ':';
            if (compassDirectionLabel) compassDirectionLabel.textContent = t.compassDirection + ':';
            if (directionTextLabel) directionTextLabel.textContent = t.directionText + ':';
            
            // 更新控制按钮文本
            const startExplorationText = document.getElementById('startExplorationText');
            const refreshLocationText = document.getElementById('refreshLocationText');
            const endJourneyText = document.getElementById('endJourneyText');
            
            if (startExplorationText) startExplorationText.textContent = t.startExploration;
            if (refreshLocationText) refreshLocationText.textContent = t.refreshLocation;
            if (endJourneyText) endJourneyText.textContent = t.endJourney;
            
            // 更新其他界面文本
            const visitedPlacesText = document.getElementById('visitedPlacesText');
            const systemLogText = document.getElementById('systemLogText');
            const clearLogsBtn = document.getElementById('clearLogsBtn');
            
            if (visitedPlacesText) visitedPlacesText.textContent = t.visitedPlaces;
            if (systemLogText) systemLogText.textContent = t.systemLog;
            if (clearLogsBtn) clearLogsBtn.textContent = t.clearLogs;
            
            // 更新城市相关按钮
            const viewAttractionsText = document.getElementById('viewAttractionsText');
            const randomRoamingText = document.getElementById('randomRoamingText');
            
            if (viewAttractionsText) viewAttractionsText.textContent = t.viewAttractions;
            if (randomRoamingText) randomRoamingText.textContent = t.randomRoaming;
            
            // 更新城市漫游相关元素
            const cityRoamingTitle = document.getElementById('cityRoamingTitle');
            const selectCityLabel = document.getElementById('selectCityLabel');
            const searchCityLabel = document.getElementById('searchCityLabel');
            const pleaseSelectCityOption = document.getElementById('pleaseSelectCityOption');
            const globalCitiesGroup = document.getElementById('globalCitiesGroup');
            const chinaCitiesGroup = document.getElementById('chinaCitiesGroup');
            const citySearch = document.getElementById('citySearch');
            const roamingStatusText = document.getElementById('roamingStatusText');
            
            if (cityRoamingTitle) cityRoamingTitle.textContent = '🌍 ' + t.cityRoaming + ':';
            if (selectCityLabel) selectCityLabel.textContent = t.selectCity + ':';
            if (searchCityLabel) searchCityLabel.textContent = t.searchCity + ':';
            if (pleaseSelectCityOption) pleaseSelectCityOption.textContent = t.pleaseSelectCity;
            if (globalCitiesGroup) globalCitiesGroup.label = '🌍 ' + t.globalCities;
            if (chinaCitiesGroup) chinaCitiesGroup.label = '🇨🇳 ' + t.chinaCities;
            if (citySearch) citySearch.placeholder = t.enterCityName;
            if (roamingStatusText) roamingStatusText.textContent = t.loadingCityInfo;
            
            // 更新导航面板按钮文本
            const navigationToggleText = document.getElementById('navigation-toggle-text');
            const navigationPanel = document.getElementById('navigationPanel');
            if (navigationToggleText && navigationPanel) {
                const isVisible = navigationPanel.classList.contains('show');
                navigationToggleText.textContent = isVisible ? 
                    (t.hideNavigationPanel || '隐藏导航面板') : 
                    (t.showNavigationPanel || '显示导航面板');
            }
            
            // 更新旅游导航生成器相关文本
            const travelGuideTitle = document.getElementById('travel-guide-title');
            const generateGuideText = document.getElementById('generate-guide-text');
            const clearPromptText = document.getElementById('clear-prompt-text');
            const resultsTitle = document.getElementById('results-title');
            const viewMapText = document.getElementById('view-map-text');
            const exportGuideText = document.getElementById('export-guide-text');
            const navigationSettingsTitle = document.getElementById('navigation-settings-title');
            const travelMapTitle = document.getElementById('travel-map-title');
            
            if (travelGuideTitle) travelGuideTitle.textContent = t.travelGuideTitle || '一句话生成旅游导航图';
            if (generateGuideText) generateGuideText.textContent = t.generateGuideText || '生成导航图';
            if (clearPromptText) clearPromptText.textContent = t.clearPromptText || '清空';
            if (resultsTitle) resultsTitle.textContent = '🎯 ' + (t.resultsTitle || '生成的旅游导航图');
            if (viewMapText) viewMapText.textContent = t.viewMapText || '查看地图';
            if (exportGuideText) exportGuideText.textContent = t.exportGuideText || '导出行程';
            if (navigationSettingsTitle) navigationSettingsTitle.textContent = t.navigationSettingsTitle || '导航设置';
            if (travelMapTitle) travelMapTitle.textContent = '🗺️ ' + (t.travelMapTitle || '旅游导航地图');
        }
        
        function generateLanguageOptions() {
            const dropdown = document.getElementById('language-dropdown');
            if (!dropdown) {
                console.error('找不到 language-dropdown 元素');
                return;
            }
            
            const languages = i18n.getSupportedLanguages();
            console.log('生成语言选项:', languages);
            
            dropdown.innerHTML = languages.map(lang => `
                <div class="language-option ${lang.code === currentLanguage ? 'active' : ''}" 
                     onclick="changeLanguage('${lang.code}')">
                    <span class="language-flag">${lang.flag}</span>
                    <span class="language-name">${lang.name}</span>
                </div>
            `).join('');
            
            console.log('语言选项生成完成，共', languages.length, '种语言');
        }
        
        function changeLanguage(langCode) {
            if (i18n.changeLanguage(langCode)) {
                currentLanguage = langCode;
                // 设置为全局变量，供iframe访问
                window.currentLanguage = langCode;
                updateLanguageUI();
                generateLanguageOptions();
                updateLanguageButton();
                toggleLanguageDropdown();
                
                // 触发语言变化事件，通知iframe
                window.dispatchEvent(new CustomEvent('languageChanged', { 
                    detail: { language: langCode } 
                }));
            }
        }
        
        function updateLanguageButton() {
            const currentLang = i18n.getCurrentLanguage();
            const langData = i18n.getSupportedLanguages().find(lang => lang.code === currentLang);
            if (langData) {
                const button = document.querySelector('.language-button');
                if (button) {
                    button.innerHTML = `${langData.flag} ${langData.name}`;
                }
            }
        }
        
        
        function checkAuthStatus() {
            const token = localStorage.getItem('access_token');
            if (token) {
                // 验证token并获取用户信息
                fetchUserInfo();
            } else {
                updateUserUI(null);
            }
        }
        
        async function fetchUserInfo() {
            try {
                const token = localStorage.getItem('access_token');
                const response = await fetch('/api/auth/me', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const user = await response.json();
                    currentUser = user;
                    updateUserUI(user);
                } else {
                    // Token无效，清除本地存储
                    localStorage.removeItem('access_token');
                    localStorage.removeItem('user_id');
                    updateUserUI(null);
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                updateUserUI(null);
            }
        }
        
        function updateUserUI(user) {
            const t = translations[currentLanguage] || translations['zh'];
            
            const userAvatarEl = document.getElementById('user-avatar');
            const userEmailEl = document.getElementById('user-email');
            const loginBtnEl = document.getElementById('login-btn');
            const registerBtnEl = document.getElementById('register-btn');
            const logoutBtnEl = document.getElementById('logout-btn');
            
            if (user) {
                // 已登录状态 - 显示成功头像
                if (userAvatarEl) {
                    userAvatarEl.textContent = '✓';
                    userAvatarEl.className = 'user-avatar logged-in';
                    userAvatarEl.title = `${user.username} (已登录)`;
                }
                if (userEmailEl) userEmailEl.textContent = user.email;
                if (loginBtnEl) loginBtnEl.classList.add('hidden');
                if (registerBtnEl) registerBtnEl.classList.add('hidden');
                if (logoutBtnEl) logoutBtnEl.classList.remove('hidden');
            } else {
                // 未登录状态 - 显示游客头像
                if (userAvatarEl) {
                    userAvatarEl.textContent = '👤';
                    userAvatarEl.className = 'user-avatar guest';
                    userAvatarEl.title = t.guest || '游客 (点击登录)';
                }
                if (userEmailEl) userEmailEl.textContent = t.notLoggedIn || '未登录';
                if (loginBtnEl) loginBtnEl.classList.remove('hidden');
                if (registerBtnEl) registerBtnEl.classList.remove('hidden');
                if (logoutBtnEl) logoutBtnEl.classList.add('hidden');
            }
            
            console.log('用户界面更新完成:', user ? '已登录' : '未登录');
        }
        
        function showAuthModal(type) {
            const modal = document.getElementById('auth-modal');
            modal.classList.remove('hidden');
            
            // 隐藏用户菜单
            const userDropdown = document.getElementById('user-dropdown');
            if (userDropdown) {
                userDropdown.classList.add('hidden');
            }
            
            // 通知iframe切换标签页
            const iframe = modal.querySelector('iframe');
            iframe.onload = function() {
                iframe.contentWindow.postMessage({ action: 'switchTab', tab: type }, '*');
            };
        }
        
        function closeAuthModal() {
            const modal = document.getElementById('auth-modal');
            modal.classList.add('hidden');
        }
        
        async function logout() {
            try {
                const token = localStorage.getItem('access_token');
                if (token) {
                    await fetch('/api/auth/logout', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    });
                }
            } catch (error) {
                console.error('登出失败:', error);
            } finally {
                // 清除本地存储
                localStorage.removeItem('access_token');
                localStorage.removeItem('user_id');
                currentUser = null;
                updateUserUI(null);
                toggleUserMenu();
            }
        }
        
        function setupAuthEventListeners() {
            // 监听来自iframe的消息
            window.addEventListener('message', function(event) {
                if (event.data.action === 'authSuccess') {
                    closeAuthModal();
                    checkAuthStatus();
                }
                // 监听关闭认证模态框的消息
                if (event.data.action === 'closeAuthModal') {
                    closeAuthModal();
                }
            });
            
            // 点击外部关闭下拉菜单
            document.addEventListener('click', function(e) {
                const languageDropdown = document.getElementById('language-dropdown');
                const languageButton = document.querySelector('.language-button');
                const userDropdown = document.getElementById('user-dropdown');
                const userButton = document.querySelector('.user-button');
                
                if (!languageDropdown.contains(e.target) && !languageButton.contains(e.target)) {
                    languageDropdown.classList.add('hidden');
                }
                
                if (!userDropdown.contains(e.target) && !userButton.contains(e.target)) {
                    userDropdown.classList.add('hidden');
                }
            });
        }
    </script>
</body>
</html>